<?php

namespace apiend\modules\business\models;

use Yii;
use yii\db\Exception;
use common\helpers\ArrayHelper;
use common\models\bill\Bill;
use common\models\bill\BillData;
use common\models\bill\BillType;
use common\models\rfid\Rfid;

/**
 * 票据信息写入完成模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class BillCompleteForm extends \common\base\Model {

    /**
     * @var string 用户UID
     */
    public $token;

    /**
     * @var string 用户UID
     */
    public $data;

    /**
     * @var object 票据类型
     */
    private $_model = null;

    /**
     * @var object 票据类型
     */
    private $_rfids = [];

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['data', 'token'], 'required'],
            [['token'], 'validateToken'],
            [['data'], 'validateData'],
        ];
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getModel() {
        if ($this->_model === null) {
            $this->_model = Bill::findByToken($this->token);
        }
        return $this->_model;
    }

    protected function getRfids() {
        return $this->_rfids;
    }

    /**
     * 格式化地点
     */
    public function validateToken($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        if ($this->getModel() == null) {
            $this->addError($attribute, '需要写入内容');
        }
    }

    /**
     * 格式化地点
     */
    public function validateData($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $data = explode(',', $this->$attribute);
        $rfids = array_unique($data);
        if (empty($rfids)) {
            $this->addError($attribute, '需要写入内容');
        } else {
            $this->_rfids = $rfids;
        }
    }

    /**
     * 保存动态信息（发布&修改）
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('提交失败');
        }
        $rfids = $this->getRfids();
        if (empty($rfids)) {
            return $this->dumpError('未检测到标签');
        }
        $model = $this->getModel();

        $transaction = Yii::$app->db->beginTransaction();
        try {
            $nums = 0;
            foreach ($rfids as $sn) {
                $_rfid = Rfid::findOne(['sn' => $sn]);
                if (!$_rfid) {
                    continue;
                }
                $_rfid->setActived();
                if (!$_rfid->save()) {
                    throw new Exception('标签生成失败');
                }
                $nums++;
            }
            if ($nums === $model->nums) {
                $model->setActived();
                if (!$model->save()) {
                    throw new Exception('票据信息保存失败');
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        if ($model->status == Bill::STATUS_ACTIVE) {
            return null;
        }
        return $model->toArray();
    }

}
